class Goods {
    constructor(data) {
        this.tbody = document.querySelector("tbody")
        this.cartTable = document.querySelector(".cartTable")
        this.selectAll = document.querySelector(".selectAll")
        this.totalNum = document.querySelector(".totalNum")
        this.money = document.querySelector(".money")
        this.content = document.querySelector("#swiper1")
        this.data = data
        this.init()
    }
    init() {
        this.render()
        this.click()
        this.join()
    }
    render() {
        this.tbody.innerHTML = ""
        let data = JSON.parse(localStorage.getItem("cart")) || []
        data.forEach(item => {
            this.tbody.innerHTML += `
            <tr>
                    <td><input type="checkbox" value="" class="select" data-id="${item.goods_id}" ${item.is_select && "checked"}/></td>
                    <td>
                        <a href="./details.html?id=${item.goods_id}">
                            <img src="${item.img_small_logo}" >
                            <span class="hide">${item.title}</span>
                        </a>
                    </td>
                    <td><span>${item.price}</span></td>
                    <td>
                        <span class="sub" data-id="${item.goods_id}">-</span>
                        <input type="text" value="${item.cart_number}" class="txt" data-id="${item.goods_id}"/>
                        <span class="add" data-id="${item.goods_id}">+</span>
                    </td>
                    <td><span class="price">${100*item.price * item.cart_number/100}元</span></td>
                    <td><span class="del" data-id="${item.goods_id}">删除</span></td>
                </tr>
            `
        });
        //全选按钮的改变
        if (data.length) {
            let res = data.every(item => item.is_select == true)
            this.selectAll.checked = res
        } else {
            this.tbody.innerHTML = "<span style='font-size:30px; color:pink;'>你的购物车空空如也！</span>"
            this.selectAll.checked = false
        }
        //底部总件数和价格的渲染
        let res = data.filter(item => item.is_select == true)
        this.totalNum.innerHTML = "0"
        this.money.innerHTML = "0"
        if (res.length) {
            let num = 0
            let my = 0
            res.forEach(item => {
                num += item.cart_number
                my += 100 * item.price * item.cart_number / 100
            })
            this.totalNum.innerHTML = num
            this.money.innerHTML = my
        }
    }
    click() {
        this.cartTable.addEventListener("click", (e) => {
            let list = JSON.parse(localStorage.getItem("cart")) || []
            let target = e.target

            //全选功能
            if (target.className == "selectAll") {
                this.tbody.innerHTML = ""
                let type = target.checked
                list.forEach(item => {
                    item.is_select = type
                })
                localStorage.setItem("cart", JSON.stringify(list))
                this.render()
            }
            //单选功能
            if (target.className == "select") {
                this.tbody.innerHTML = ""

                let id = target.dataset.id
                let index = list.findIndex(item => item.goods_id == id)
                list[index].is_select = !list[index].is_select

                localStorage.setItem("cart", JSON.stringify(list))
                this.render()
            }

            //减少商品数量功能
            if (target.className == "sub") {

                let myId = target.dataset.id
                let index = list.findIndex(item => item.goods_id == myId)
                if (list[index].cart_number > 1) {
                    list[index].cart_number--
                    localStorage.setItem("cart", JSON.stringify(list))
                    this.render()
                }

            }
            //增加商品数量功能
            if (target.className == "add") {
                let myId = target.dataset.id
                let index = list.findIndex(item => item.goods_id == myId)
                if (list[index].cart_number < list[index].goods_number) {
                    list[index].cart_number++
                    localStorage.setItem("cart", JSON.stringify(list))
                    this.render()
                }
            }

            //删除功能
            if (target.className == "del") {
                let myId = target.dataset.id
                let index = list.findIndex(item => item.goods_id == myId)
                list.splice(index, 1)
                localStorage.setItem("cart", JSON.stringify(list))
                this.render()
            }

            //选中删除功能
            if (target.className == "dlAll") {
                list = list.filter(item => item.is_select == false)
                localStorage.setItem("cart", JSON.stringify(list))
                this.render()
            }



        }, false)
    }
    join() {
        this.content.addEventListener("click", (e) => {
            let target = e.target
            if (target.className == "btn") {
                let data = this.data
                let myId = target.dataset.id
                let list = JSON.parse(localStorage.getItem("cart")) || []
                // 通过myId来获取到data里面的goods信息
                let index = data.findIndex(item => item.goods_id == myId)
                let goods = data[index]
                if (list.length) {
                    //找到data里面和myId相同的
                    let res = list.findIndex(item => {
                        return item.goods_id == myId
                    })
                    //通过res的值来判断是否找到匹配的值
                    if (res >= 0) {
                        list[res].cart_number++
                        localStorage.setItem("cart", JSON.stringify(list))

                    } else {
                        goods.cart_number = 1
                        list.push(goods)
                        localStorage.setItem("cart", JSON.stringify(list))
                    }
                } else {
                    goods.cart_number = 1
                    list.push(goods)
                    localStorage.setItem("cart", JSON.stringify(list))
                }
                this.render()
            }
        }, false)
    }
}

//获取商品数据
require(['./config'], () => {
    require(["aj"], () => {
        getAjax({
                url: "../libs/goods.json"
            })
            .then((data) => {
                let list = JSON.parse(data)
                list = list.slice(0, 90)
                // console.log(list)
                new Goods(list)
            })
    })
})


//回到顶部的类
class BackTop {
    constructor() {
        this.btn = document.querySelector(".backTop .icon")
        this.init()
    }
    init() {
        this.click()
    }
    click() {

        this.btn.onclick = () => {
            document.documentElement.scrollTop = 0
        }
    }
}
new BackTop()


require(['./config'], () => {
    require(['myCookie'], () => {
        // 顶部登录名字
        let user = document.querySelector(".user")

        function inital() {
            if (getCookie("userName")) {
                user.innerHTML = getCookie("userName")
                // span.innerHTML = getCookie("userName")
            }
        }
        inital()
        //猜你喜欢
    })
})


//猜你喜欢
var mySwiper1 = new Swiper('#swiper1', {
    direction: 'horizontal', // 水平切换选项
    loop: false, // 循环模式选项

    // 如果需要前进后退按钮
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    }
})

//获取数据
require(['./config'], () => {
    require(["aj"], () => {
        getAjax({
                url: "../libs/goods.json"
            })
            .then((data) => {
                let list = JSON.parse(data)
                let list1 = list.slice(80, 85)
                let list2 = list.slice(85, 90)
                //渲染数据
                let ul1 = document.querySelector("#swiper1 #content1")
                let ul2 = document.querySelector("#swiper1 #content2")

                // console.log(ul);
                list1.forEach(item => {
                    ul1.innerHTML += `<li>
                                                    <img src="${item.img_big_logo}" alt="">
                                                    <p class="des">${item.title}</p>
                                                    <p class="price">￥:${item.price}</p>
                                                    <button class="btn" data-id="${item.goods_id}">加入购物车</button>
                                                </li>`
                });
                list2.forEach(item => {
                    ul2.innerHTML += `<li>
                                                    <img src="${item.img_big_logo}" alt="">
                                                    <p class="des">${item.title}</p>
                                                    <p class="price">￥:${item.price}</p>
                                                    <button class="btn" data-id="${item.goods_id}">加入购物车</button>
                                                </li>`
                });
            })
    })
})